package com.qianxun.module.datasource1.common.service;

import com.qianxun.framework.common.constant.SystemConstant;
import com.qianxun.framework.common.util.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.List;

/**
 * 邮箱服务，用于将错误信息通知到管理员
 * @author: huwei
 * @date: 2019/12/10 11:22
 * @version: 1.0.0
 */
@Slf4j
@Service
@ConfigurationProperties(prefix = "mail")
public class MailService {
    /**
     * 开通邮箱服务的账户
     */
    private String username;
    /**
     * 开通邮箱服务的账户密码
     */
    private String password;
    /**
     * 邮件来之哪个邮箱
     */
    private String from;
    /**
     * 接收用户邮箱
     */
    private List<String> toList;

    public void send(String subject,String message){
        String wrapperSubject = wrapperSubject(subject);
        toList.forEach(x->{
            sendMailTo(username ,password ,from ,x ,wrapperSubject ,message);
        });
    }

    private String wrapperSubject(String subject){
        return SystemConstant.get("system-name") + "系统：" + subject;
    }

    private void sendMailTo(String username ,String password ,String from ,String to ,String subject ,String message) {
        log.error("发送邮件到：".concat(to).concat(",主题：".concat(subject).concat("; 内容：").concat(htmlMail(message))));
        try {
            MailUtil.build163(username ,password).send(from, to, subject, htmlMail(message));
            log.error("邮件发送成功");
        }catch (MessagingException e){
            log.error("发送邮件失败，主题：".concat(subject).concat("； 内容：").concat(htmlMail(message)));
        }
    }

    private String htmlMail(String message){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("<span>");
        stringBuffer.append(message);
        stringBuffer.append("</span>");

        return stringBuffer.toString();
    }
}
